package com.jse;

import java.time.Instant;
import java.util.ResourceBundle;

public class Log implements System.Logger {

    private String name="jse";
    private static Level LEVEL=Level.DEBUG;
    private final static Cache<String,Log> CACHE=new Cache<>(64);

    public Log(){}
    public Log(String name){this.name=name;}
    public Log(Class<?> c){this.name=c.getName();}

    public static Log get(String name){Log log=CACHE.get(name);if(log==null) {log=new Log(name);CACHE.put(name, log);}return log;}
    public static Log get(){return get(Thread.currentThread().getStackTrace()[1].getClassName());}
    public static Log get(Class<?> c){return get(c.getName());}
    public static Log getLogger(String name) {return get(name);}

    @Override
    public String getName() {return name;}

    @Override
    public boolean isLoggable(Level level) {return level.compareTo(LEVEL)>-1;}

    public void trace(String s,Object...args){log(Level.TRACE, null, s, args);}
    public void debug(String s,Object...args){log(Level.DEBUG, null, s, args);}
    public void info(String s,Object...args){log(Level.INFO, null, s, args);}
    public void warn(String s,Object...args){log(Level.WARNING, null, s, args);}
    public void error(String s,Object...args){log(Level.ERROR, null, s, args);}

    @Override
    public void log(Level level, ResourceBundle bundle, String format, Object... params) {
    	boolean isf=params!=null&&params.length>0;
    	if(isf){
    		if(format.indexOf("{0}")!=-1)format=java.text.MessageFormat.format(format,params);
    		else format=format.replace("{}","%s").formatted(params);
    	}
    	log(level, bundle, format, (Throwable)null);
    }

    @Override
    public void log(Level level, ResourceBundle bundle, String msg, Throwable e) {
    	if(!isLoggable(level))return;
    	if(msg.charAt(0)=='-')System.out.println(msg);//不追加前缀
		else System.out.println("%s [%s] [%s] [%s] %s".formatted(Instant.now().toString().substring(0,23),
				level,Jse.name,name,msg));
		if(e!=null) {
			e.printStackTrace();
		}
    }
	
}
